package cn.net.dckj.web.controller.common;

import cn.net.dckj.common.config.ServerConfig;
import cn.net.dckj.common.core.domain.AjaxResult;
import cn.net.dckj.common.core.domain.JsonData;
import cn.net.dckj.common.utils.StringUtils;
import cn.net.dckj.common.utils.file.FileUploadUtils;
import cn.net.dckj.common.utils.file.FileUtils;
import cn.net.dckj.common.utils.file.MimeTypeUtils;
import cn.net.dckj.common.utils.file.ftp.FTPProperties;
import cn.net.dckj.common.utils.file.ftp.FTPUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 通用请求处理
 *
 * @author dckj
 */
@Controller
public class CommonController {
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private FTPProperties ftpProperties;

    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     * @param delete   是否删除
     */
    @GetMapping("common/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) {
        try {
            if (!FileUtils.isValidFilename(fileName)) {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePathName = FileUtils.getAbsDownloadPath(fileName);

            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, realFileName));
            FileUtils.writeBytes(filePathName, response.getOutputStream());
            if (delete) {
                FileUtils.deleteFile(filePathName);
            }
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 通用下载请求
     *
     * @param ftpPathName ftp服务器文件地址
     * @param fileName    文件名称
     */
    @GetMapping("common/ftpDownload")
    public void ftpFileDownload(String ftpPathName, String fileName, HttpServletRequest request, HttpServletResponse response) {
        try {
            if (StringUtils.isEmpty(ftpPathName)) {
                throw new Exception("未指定下载文件所在文件服务器位置，无法下载！");
            }
            if (StringUtils.isNotEmpty(fileName)) {
                if (!FileUtils.isValidFilename(fileName)) {
                    throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
                }
            } else {
                fileName = ftpPathName.substring(ftpPathName.lastIndexOf("/") + 1);
            }

            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, fileName));
            FTPUtils.getInstance().downFile(ftpPathName, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载[" + ftpPathName + "]文件失败", e);
        }
    }

    /**
     * 通用上传请求
     */
    @PostMapping("/common/upload")
    @ResponseBody
    public AjaxResult uploadFile(MultipartFile file) throws Exception {
        try {
            // 上传文件真实名称
            String fileName = file.getOriginalFilename();
            // 上传文件路径
            String filePath = ftpProperties.getUploadUrl();
            // 上传并返回保存文件路径名称
            String filePathName = FTPUtils.getInstance().uploadFile(filePath, file);
            /*String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() +
                    request.getContextPath() + Global.getPreviewUrl() + filePathName;*/
            // 预览文件地址
            String url = serverConfig.getUrl() + FTPUtils.getInstance().getPreviewUrl(filePathName);
            // 下载文件地址
            String downloadUrl = serverConfig.getUrl() + FTPUtils.getInstance().getDownloadUrl(filePathName, fileName);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileName);
            ajax.put("filePathName", filePathName);
            ajax.put("url", url);
            ajax.put("downloadUrl", downloadUrl);
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 通用上传请求,不改变文件名
     */
    @PostMapping("/common/uploadNotChangeName")
    @ResponseBody
    public AjaxResult uploadFileNotChangeName(MultipartFile file) throws Exception {
        try {
            // 上传文件真实名称
            String fileName = file.getOriginalFilename();
            // 上传文件路径
            String filePath = ftpProperties.getUploadUrl();
            // 上传并返回保存文件路径名称
            String filePathName = FTPUtils.getInstance().uploadFile(filePath, file, false);
            // 预览文件地址
            String url = serverConfig.getUrl() + FTPUtils.getInstance().getPreviewUrl(filePathName);
            // 下载文件地址
            String downloadUrl = serverConfig.getUrl() + FTPUtils.getInstance().getDownloadUrl(filePathName, fileName);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileName);
            ajax.put("filePathName", filePathName);
            ajax.put("url", url);
            ajax.put("downloadUrl", downloadUrl);
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 获取图片/mp4视频/pdf预览文件路径
     *
     * @param ftpPathName ftp文件服务器文件路径名称
     * @return
     * @throws Exception
     */
    @GetMapping("/common/preview")
    public void preview(String ftpPathName, HttpServletResponse response) {
        try {
            if (StringUtils.isEmpty(ftpPathName)) {
                throw new Exception("未指定预览文件所在文件服务器位置，无法预览！");
            }
            String fileType = ftpPathName.substring(ftpPathName.lastIndexOf(".") + 1);
            fileType = fileType.toLowerCase();
            boolean isAllowedStream = FileUploadUtils.isAllowedExtension(fileType, MimeTypeUtils.ALLOWED_STREAM_EXTENSION);
            if (isAllowedStream) {
                FTPUtils.getInstance().downFile(ftpPathName, response.getOutputStream());
            } else {
                throw new Exception("预览文件格式不正确或不支持，无法预览！");
            }
        } catch (Exception e) {
            log.error("预览[" + ftpPathName + "]文件失败", e);
        }
    }

    /**
     * 手机端 获取图片/mp4视频/pdf预览文件路径
     *
     * @param ftpPathName ftp文件服务器文件路径名称
     * @return
     * @throws Exception
     */
    @GetMapping("/mobile/common/preview")
    public void frontPreview(String ftpPathName, HttpServletResponse response) {
        preview(ftpPathName, response);
    }

    /**
     * 获取需要转换的预览文件路径(doc,docx,xls,xlsx)
     *
     * @param ftpPathName ftp文件服务器文件路径名称
     * @return
     * @throws Exception
     */
    @GetMapping("/common/previewChangeType")
    @ResponseBody
    public AjaxResult previewChangeType(String ftpPathName) {
        try {
            if (StringUtils.isEmpty(ftpPathName)) {
                return AjaxResult.error("未指定预览文件所在文件服务器位置，无法预览！");
            }
            String url = "";
            String fileType = ftpPathName.substring(ftpPathName.lastIndexOf(".") + 1);
            fileType = fileType.toLowerCase();
            boolean isAllowedPreview = FileUploadUtils.isAllowedExtension(fileType, MimeTypeUtils.ALLOWED_PREVIEW_EXTENSION);
            if (isAllowedPreview) {
                if ("xls".equals(fileType) || "xlsx".equals(fileType)) {
                    //url = JodconverterUtil.file2Html(ftpPathName);
                } else {
                    //url = JodconverterUtil.convertFileToPdf(ftpPathName);
                }
            } else {
                return AjaxResult.error("预览文件格式不正确或不支持，无法预览！");
            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 前台调用判断session超时状态
     */
    @GetMapping("common/sessionTimeout")
    @ResponseBody
    public JsonData sessionTimeout() {
        return new JsonData().setCode(0);
    }

    /**
     * 本地资源通用下载
     */
    /*@GetMapping("/common/download/resource")
    public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        // 本地资源路径
        String localPath = Global.getProfile();
        // 数据库资源地址
        String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
        // 下载名称
        String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition",
                "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, downloadName));
        FileUtils.writeBytes(downloadPath, response.getOutputStream());
    }*/
}
